package com.starblink.android.basic.user

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.provider.Settings
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.config.GuangConfig
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.charles.CharlesConfig
import com.starblink.android.charles.CharlesManager
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.Md5Util
import com.starblink.rocketreserver.FetchAccountInfoQuery
import java.util.*

object UserDataCenter {

    var successUploadOtherSpm = false
    private const val tokenKey = "guangToken"
    private const val localCountryKey = "localCountryKey"
    private const val localCountryCodeKey = "localCountryCodeKey"
    private const val accountInfoKey = "accountInfoTagKey"
    const val subscribeRemindMe_Brand = "subscribeRemindMeBrand"
    const val subscribeRemindMe_Store = "subscribeRemindMeStore"
    const val subscribeRemindMe_Good = "subscribeRemindMeGood"
    const val subscribeEmail = "subscribeEmail"
    const val HOME_TAB_INDEX_NOSPM =
        "HOME_TAB_INDEX_NOSPM" //控制是否从其它地方切换到心愿单页面时上报tab的点击事件 true-不上报 false-上报
    val LOCAL_COUNTRY_CODE = getFlutterCountry()

    ///邀请码
    var inviteCode = ""

    ///设备id
    var deviceId = ""

    //首页tab的真实位置 0为第一个
    var currentIndex = 0

    //home是否加载了类目
    var loadedCategory: Boolean = false

    //home是否存在类目
    var existCategory: Boolean = false


    //首页缓存设置
    const val HOME_CACHE_BANNER_DATA = "HOME_CACHE_BANNER_DATA"
    const val HOME_CACHE_DISCOUNT_DATA = "HOME_CACHE_DISCOUNT_DATA"
    const val HOME_CACHE_BRAND_DATA = "HOME_CACHE_BRAND_DATA"
    const val HOME_CACHE_PRODUCT_DATA = "HOME_CACHE_PRODUCT_DATA"

    private var homeCacheRefresh = hashMapOf(
        HOME_CACHE_BANNER_DATA to false,
        HOME_CACHE_DISCOUNT_DATA to false,
        HOME_CACHE_BRAND_DATA to false,
        HOME_CACHE_PRODUCT_DATA to false,
    )


    fun isLogin(): Boolean {
        return getToken() != null
    }


    //localCountryKey

    fun putLocalCountry(lc: String) {
        SkStorage.put(localCountryKey, lc)
    }

    /**
     * app唯一获取country入口
     */
    fun getLocalCountry(): String {
        return SkStorage.getString(localCountryKey, null) ?: getFlutterCountry()
    }

    //device_info_utils.dart 参考flutter处理
    //  // country: \"zh_CN_#Hans\", language: \"zh_CN_#Hans\"
    //  // country: \"zh_AL_#Hans\", language: \"zh_AL_#Hans\"
    //  // country: \"en_CN\", language: \"en_CN\"
    private fun getFlutterCountry(): String {
        var ctr = Locale.getDefault().toString()
        if (ctr.contains("_")) {
            var arr = ctr.split("_")
            return if (arr.isNotEmpty()) {
                arr[1]
            } else {
                ctr
            }
        }
        return ctr
    }


    //localCountryCodeKey
    fun putLocalCountryCode(lcc: String) {
        SkStorage.put(localCountryCodeKey, lcc)
    }

    /**
     * app唯一获取country code入口
     */
    fun getLocalCountryCode(): String {
//
//        Locale.getDefault().getLanguage()       ---> en
//        Locale.getDefault().getISO3Language()   ---> eng
//        Locale.getDefault().getCountry()        ---> US
//        Locale.getDefault().getISO3Country()    ---> USA
//        Locale.getDefault().getDisplayCountry() ---> United States
//        Locale.getDefault().getDisplayName()    ---> English (United States)
//        Locale.getDefault().toString()          ---> en_US
//        Locale.getDefault().getDisplayLanguage()---> English

        return SkStorage.getString(localCountryCodeKey, null)
            ?: Locale.getDefault().country

//        return Locale.getDefault().country
    }

    private fun getCountryCodeDevice(countryName: String): String {
        val isoCountryCodes = Locale.getISOCountries()
        for (code in isoCountryCodes) {
            val locale = Locale("", code)
            if (countryName.equals(locale.displayCountry, ignoreCase = true)) {
                return code
            }
        }
        return ""
    }

    //UserInfo


    /**
     * 获取用户信息
     * @note 注意：每次调用getAccountInfo()方法，都会返回一个新的FetchAccountInfo对象
     */
    open fun getAccountInfo(): FetchAccountInfoQuery.FetchAccountInfo? {
        return if (SkStorage.getString(accountInfoKey, null) == null) {
            null
        } else {
            GsonUtils.fromJson(
                SkStorage.getString(accountInfoKey, null),
                FetchAccountInfoQuery.FetchAccountInfo::class.java
            )
        }

    }

    fun setAccountInfo(info: FetchAccountInfoQuery.FetchAccountInfo) {
        SkStorage.put(
            accountInfoKey,
            GsonUtils.toJson(info, FetchAccountInfoQuery.FetchAccountInfo::class.java)
        )
    }

    private fun clearAccountInfo() {
        SkStorage.remove(accountInfoKey)
    }

    //token
    fun putToken(tk: String) {
        SkStorage.put(tokenKey, tk)
        SkGqlClient.resetClient()
        //跨进程resetClient
        BridgeUtil.sendCommonData(BridgeCommand.Common.resetClient)
        //登录后需要设置订阅邮箱
        CommonMutateManage.subscribeEmailAfterLogin()
    }

    fun getToken(): String? {
        return SkStorage.getString(tokenKey, null)
    }

    /**
     * 清除所有用户信息
     */
    fun clearToken() {
        SkStorage.remove(tokenKey)
        SkGqlClient.resetClient()
        clearAccountInfo()
        //跨进程resetClient
        BridgeUtil.sendCommonData(BridgeCommand.Common.resetClient)
    }

    private val userAgentMap: HashMap<String, String> = HashMap()
    private var userAgentMapString: String = "##"

    fun clearUserAgentData() {
        userAgentMap.clear() //退出登录需清理UA
    }

    ///初始化UserAngent
    fun getUserAgentData(): String {
        if (userAgentMap.isEmpty()) {
            userAgentMap["OSVersion"] = Build.VERSION.RELEASE
            userAgentMap["deviceId"] = getDeviceId(CommUtils.getContext())
            userAgentMap["phoneModel"] = Build.MODEL
            userAgentMap["brand"] = Build.BRAND
            userAgentMap["appVersion"] = AppUtils.getAppVersionName()
            userAgentMap["appName"] = AppUtils.getAppName()
            userAgentMap["packageName"] = AppUtils.getAppPackageName()
            userAgentMap["buildNumber"] = AppUtils.getAppVersionCode().toString() + ""
            userAgentMap["statusHeight"] =
                CommUtils.px2dip(BarUtils.getStatusBarHeight()).toString() + ""
            userAgentMap["bottomSafeHeight"] = "0"
            userAgentMap["darkModel"] = "false"
            userAgentMap["country"] = Locale.getDefault().toString()
            userAgentMap["countryCode"] = getLocalCountryCode()
            userAgentMap["captureStatus"] =
                if (CharlesManager.isUploadPacketInfo()) "1" else "0" //抓包开关
            userAgentMap["mockStatus"] =
                if (CharlesManager.isMockPacketInfo()) "1" else "0" //Mock开关
            userAgentMap["charlesHostUrl"] = CharlesConfig.hostUrl

            if (isLogin()) {
                userAgentMap["appToken"] = getToken()!!
                userAgentMap["appLogin"] = "true"
                if (getAccountInfo()?.id != null) {
                    userAgentMap["userId"] = getAccountInfo()!!.id
                }
                if (getAccountInfo()?.userName != null) {
                    userAgentMap["userName"] = getAccountInfo()!!.userName!!
                }
            } else {
                userAgentMap["appLogin"] = "false"
            }
            var sb: StringBuilder = StringBuilder()
            userAgentMapString = "##"
            var i = 1
            userAgentMap.forEach { it ->
                if (i == userAgentMap.size) {
                    sb.append("${it.key}=${it.value}");
                } else {
                    sb.append("${it.key}=${it.value}&");
                }
                i++
            }
            userAgentMapString = userAgentMapString.plus(sb.toString())
        }
        return userAgentMapString
    }

    /**
     * 所有的deviceID都要从这里取 flutter的设备id前加入了and_的前缀
     * @param context
     * @return
     */
    @SuppressLint("HardwareIds")
    fun getDeviceId(context: Context): String {
        return deviceId.ifEmpty {
            var androidID = SkStorage.getString(GuangConfig.GUANG_DEVICE_ID, "")
            deviceId =
                if (androidID.isNullOrEmpty()) {
                    val androidID =
                        Settings.Secure.getString(
                            context.contentResolver,
                            Settings.Secure.ANDROID_ID
                        )
                    if (androidID.isNullOrEmpty()) {
                        "and_" + UUID.randomUUID().toString()
                    } else {
                        try {
                            "and_" + Md5Util.md5(androidID)
                        } catch (e: java.lang.Exception) {
                            e.printStackTrace()
                            "and_$androidID"
                        }
                    }
                } else {
                    androidID
                }
            SkStorage.put(GuangConfig.GUANG_DEVICE_ID, deviceId)
            return deviceId
        }
    }


    //订阅弹框提醒
    fun putSubscribeRemindMe(key: String, remindMe: Boolean) {
        SkStorage.put(key, remindMe)
    }

    fun getSubscribeRemindMe(key: String): Boolean {
        return SkStorage.getBoolean(key, true)
    }

    //存储订阅邮箱
    fun putSubscribeEmial(email: String) {
        SkStorage.put(subscribeEmail, email)
    }

    fun getSubscribeEmail(): String {
        return SkStorage.getString(subscribeEmail, "") ?: ""
    }

    private const val NAV_BAR_IS_NEW_DAY = "NAV_BAR_IS_NEW_DAY"
    fun isNewDay(scene: String = ""): Boolean {

        val key = if (scene.isEmpty()) NAV_BAR_IS_NEW_DAY else NAV_BAR_IS_NEW_DAY + "_$scene"

        var nowDay = CommUtils.getYearMonthDay()

        var lastDay = SkStorage.getString(key, null)


        var newDay: Boolean

        if (lastDay == null) {
            SkStorage.put(key, nowDay)
            newDay = true
        } else {
            if (nowDay == lastDay) {
                newDay = false
            } else {
                SkStorage.put(key, nowDay)
                newDay = true
            }
        }

        if (newDay) {
            resetQueryCache()
        }

        return newDay
    }

    //查询首页接口是否要缓存 当然也可以放其他的
    fun queryByCache(tagStr: String): Boolean {
        return SkStorage.getBoolean(tagStr, false) && !(homeCacheRefresh[tagStr]!!)
    }

    //设置首页缓存
    fun setQueryByCache(tagStr: String) {
        homeCacheRefresh[tagStr] = true
        SkStorage.put(tagStr, true)
    }

    //重置首页缓存判断
    fun resetQueryCache() {
        for ((str, _) in homeCacheRefresh) {
            homeCacheRefresh[str] = false
            SkStorage.put(str, false)
        }
    }

    fun updateDay() {
        SkStorage.put(NAV_BAR_IS_NEW_DAY, CommUtils.getYearMonthDay())
    }

    const val NEW_DAY_SCENE_DISCOUNT = "1"
}